package com.cqcet.wenchuang.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cqcet.wenchuang.entity.LoginAdmin;
import com.cqcet.wenchuang.entity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus填充公共字段处理器
 */
@Slf4j
@Component
public class MateObjectHandler implements MetaObjectHandler {

    /**
     * 获取当前用户id, 用户未登录返回null
     * @return
     */
    private Long getCurrentUserId() {
        UsernamePasswordAuthenticationToken authentication;
        if (SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken) {
            return null;
        }
        authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            //安慰报错
            throw new RuntimeException("未知错误");
        }
        Long userId;
        if (principal instanceof LoginAdmin) {
            LoginAdmin loginAdmin = (LoginAdmin) principal;
            userId = loginAdmin.getAdmin().getId();
        } else {
            LoginUser loginUser = (LoginUser) principal;
            userId = loginUser.getUser().getId();
        }
        return userId;
    }

    /**
     * 新增操作公共字段
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("新增公共字段填充...");
        log.info(metaObject.toString());
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        Long userId = getCurrentUserId();
        metaObject.setValue("createUser", userId);
        metaObject.setValue("updateUser", userId);
    }

    /**
     * 更新修改时间和修改人
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("更新公共字段填充方法...");
        log.info(metaObject.toString());
        metaObject.setValue("updateTime", LocalDateTime.now());
        Long userId = getCurrentUserId();
        metaObject.setValue("updateUser", userId);
    }
}
